package org.jetnuke.modules.news;

import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.entities.MainConfig;
import org.jetnuke.entities.Stories;
import org.jetnuke.util.JetUtil;

public class Print implements IAction {
	private final static Logger s_log = Logger.getLogger(Print.class);
	int id;

	public void setId(int id) {
		this.id = id;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jetnuke.common.IAction#exec(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse,
	 *      org.apache.velocity.VelocityContext, org.jetnuke.common.IModuleInfo,
	 *      java.lang.String, org.jetnuke.common.IUserInfo,
	 *      org.jetnuke.common.IAdminInfo)
	 */
	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {

		MainConfig mainConfig = (MainConfig) request
				.getAttribute("MAIN_CONFIG");
		String url = mainConfig.getNUKEURL();
		vc.put("url", url);
		Stories st = DataAccessDriver.getInst().newStoriesDAO().retrieveByPK(id);
		vc.put("topic", DataAccessDriver.getInst().newTopicsDAO().retrieveByPK(st.getTOPIC()));
		vc.put("story", st);

		StringWriter sw = new StringWriter(1024 * 4);
		try {
			Template t = Velocity.getTemplate("modules/news/print.vm");
			t.merge(vc, sw);
		} catch (Exception e) {
			s_log.error(e);
		}
		JetUtil.manageReponseCookies(vc,response);
		response.setContentType("text/html");
		String txt = sw.toString();
		
		PrintWriter pw = response.getWriter();
		pw.write(txt);
		return null;
	}

}
